using System.Collections.Concurrent;
using Google.Protobuf.WellKnownTypes;
using Grpc.Core;
using Model;

namespace _2GrpcUse.Services;

public record OrderEntity(int Id, string Name, string Description, double Price);

public class OrderService : Order.OrderService.OrderServiceBase
{
	private readonly ILogger<OrderService> _logger;
	private static readonly ConcurrentDictionary<int, OrderEntity> _orders = new();
	private static volatile int _id;

	public OrderService(ILogger<OrderService> logger)
	{
		_logger = logger;
	}

	public override async Task<CreateOrderResponse> CreateOrder(CreateOrderRequest request, ServerCallContext context)
	{
		var resp = new CreateOrderResponse();
		if (string.IsNullOrWhiteSpace(request.Name))
		{
			resp.Error = "订单名称是必须的";
			return resp;
		}

		if (request.Price <= 0)
		{
			resp.Error = "订单价格必须大于0";
			return resp;
		}

		if ("error".Equals(request.Name))
		{
			throw new RpcException(new Status(StatusCode.Internal, "服务器内部错误"));
		}

		var genId = Interlocked.Increment(ref _id);
		_orders.TryAdd(genId, new OrderEntity(genId, request.Name, request.Description, request.Price));

		await Task.Yield();
		resp.OrderId = genId;
		resp.Success = true;
		return resp;
	}

	public override Task<GetAllOrdersResponse> GetAllOrders(Empty request, ServerCallContext context)
	{
		return Task.FromResult(new GetAllOrdersResponse
		{
			Success = true,
			Orders =
			{
				_orders.Values.Select(x => new OrderModel()
				{
					OrderId = x.Id,
					Name = x.Name,
					Description = x.Description,
					Price = x.Price
				})
			}
		});
	}

	public override async Task<GetOrderByIdResponse> GetOrderById(OrderIdRequest request, ServerCallContext context)
	{
		if (!_orders.TryGetValue(request.OrderId, out OrderEntity? value))
		{
			throw new RpcException(new Status(StatusCode.NotFound, "订单不存在"));
		}

		return new GetOrderByIdResponse
		{
			Success = true,
			Order = new OrderModel
			{
				OrderId = request.OrderId,
				Name = value.Name,
				Description = value.Description,
				Price = value.Price
			}
		};
	}

	public override Task<DeleteOrderResponse> DeleteOrder(OrderIdRequest request, ServerCallContext context)
	{
		if (!_orders.TryGetValue(request.OrderId, out OrderEntity? value))
		{
			throw new RpcException(new Status(StatusCode.NotFound, "订单不存在"));
		}

		_orders.TryRemove(request.OrderId, out _);
		return Task.FromResult(new DeleteOrderResponse
		{
			Success = true,
			OrderId = request.OrderId,
		});
	}
}
